#encoding=utf8
'''
Created on Apr 14, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django.db import models
from django.contrib.auth.models import User
import settings
from django.utils import timezone


class NoticeManager(models.Manager):
    def send_notice(self, subject, content, receiver, sent_time=None,
        sender=None):
        try:
            r = User.objects.get(username=receiver.split('@')[0])
            s = User.objects.get(username=sender.split('@')[0]) if sender else None
        except Exception, e:
            print e
            return
        self.create(sender=s, receiver=r, subject=subject, content=content,
            sent_time=sent_time or timezone.now())

    def notice_manager(self, subject, content, sent_time=None, sender=None):
        for i in settings.MANAGERS:
            self.send_notice(subject, content, i[1], sent_time, sender)


class Notice(models.Model):
    sender = models.ForeignKey(User, verbose_name='Sender', related_name='sender',
        null=True, blank=True, limit_choices_to={'is_active': True, 'is_staff': True})
    receiver = models.ForeignKey(User, verbose_name='Receiver',
        related_name='receiver', null=True, blank=True,
        limit_choices_to={'is_active': True, 'is_staff': True})
    subject = models.CharField('Subject', max_length=200)
    content = models.TextField('Content')
    read = models.BooleanField('Read?', default=False)
    create_time = models.DateTimeField('Created at', auto_now_add=True)
    sent_time = models.DateTimeField('Sent at', null=True, blank=True)
    showed = models.BooleanField('Showed by desktop notification', default=False)

    objects = NoticeManager()

    def __unicode__(self):
        return 'Notification from %s' % (self.sender or 'system')

    class Meta:
        ordering = ('read',)


class ReportReceiver(models.Model):
    name = models.CharField('Name', max_length=100, null=True, blank=True)
    email = models.EmailField('Email Address')
    is_active = models.BooleanField('Active', default=False)
    create_time = models.DateTimeField('Created At', auto_now_add=True)

    def __unicode__(self):
        return self.name or self.email

    class Meta:
        verbose_name = 'Weekly Report Receipient'
        verbose_name_plural = 'Weekly Report Receipients'
        ordering = ('-is_active',)
